import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../core/storage/http_util.dart';

class NetworkDemoPage extends StatefulWidget {
  const NetworkDemoPage({super.key});

  @override
  State<NetworkDemoPage> createState() => _NetworkDemoPageState();
}

class _NetworkDemoPageState extends State<NetworkDemoPage> {
  final TextEditingController _urlController = TextEditingController();
  final TextEditingController _paramsController = TextEditingController();
  String _selectedMethod = 'GET';
  final List<String> _methods = ['GET', 'POST', 'PUT', 'DELETE'];
  String _response = '';
  bool _isLoading = false;

  Future<void> sendRequest() async {
    setState(() {
      _isLoading = true;
      _response = '';
    });

    try {
      final httpUtil = HttpUtil();
      dynamic response;

      final params = _paramsController.text.isNotEmpty
          ? jsonDecode(_paramsController.text)
          : null;

      switch (_selectedMethod) {
        case 'GET':
          response = await httpUtil.get(_urlController.text);
          break;
        case 'POST':
          response = await httpUtil.post(_urlController.text, body: params);
          break;
        case 'PUT':
          response = await httpUtil.put(_urlController.text, body: params);
          break;
        case 'DELETE':
          response = await httpUtil.delete(_urlController.text);
          break;
      }

      setState(() {
        _response = const JsonEncoder.withIndent('  ').convert(response);
      });
    } catch (e) {
      setState(() {
        _response = '错误: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('网络请求示例'),
        actions: [
          IconButton(
            icon: const Icon(Icons.clear),
            onPressed: () {
              setState(() {
                _urlController.clear();
                _paramsController.clear();
                _response = '';
              });
            },
            tooltip: '清除所有',
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _urlController,
              decoration: const InputDecoration(
                labelText: 'URL',
                hintText: 'https://api.example.com/data',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.link),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: DropdownButton<String>(
                      value: _selectedMethod,
                      isExpanded: true,
                      underline: Container(),
                      items: _methods.map((String method) {
                        return DropdownMenuItem<String>(
                          value: method,
                          child: Text(method),
                        );
                      }).toList(),
                      onChanged: (String? newValue) {
                        if (newValue != null) {
                          setState(() {
                            _selectedMethod = newValue;
                          });
                        }
                      },
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _paramsController,
              maxLines: 3,
              decoration: const InputDecoration(
                labelText: '参数 (JSON格式)',
                hintText: '{"key": "value"}',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.code),
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: _isLoading ? null : sendRequest,
              icon: _isLoading
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    )
                  : const Icon(Icons.send),
              label: Text(_isLoading ? '请求中...' : '发送请求'),
            ),
            const SizedBox(height: 16),
            if (_response.isNotEmpty) ...[
              const Divider(),
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SingleChildScrollView(
                    child: SelectableText(
                      _response,
                      style: const TextStyle(fontFamily: 'monospace'),
                    ),
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _urlController.dispose();
    _paramsController.dispose();
    super.dispose();
  }
}
